﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using YXH_Tools_Files.Tools_CSV;
using YXH_Tools_Files.Tools_DirectoryandFile;
using YXH_Tools_Files.Tools_EdgeComputing;
using YXH_Tools_Files.Tools_MappingClass;

namespace YXH_Tools_Files.Tools_Excute
{
    public static class AutoExcute
    {
        public static async Task<List<string>> YXHAutoExcuteCsvAsync(AutoProcessModal row)
        {
            List<string> list = new List<string>();//专用于输出程序计算过程中的错误信息
            //先创建输出文件夹
            Directory.CreateDirectory(row.savedatapath);
            //改为小写，然后按‘，’分割
            var configuredfolders=row.savedatapath.ReComma().ReName().Split(',');
            var cleannumreg=row.cleannumreg.ReComma().Split(',');
            var cleanstringreg = row.cleanstringreg.ReComma().Split(',');
            if (configuredfolders.Length > 0)
            {
                //获得用户需要合并的源数据日期文件夹列表
                var ds = Tools_Excute_CSVCombine.YXHGetProcessedFolders(row.originaldatapath, row.savedatapath, configuredfolders);
                if (ds != null)
                {
                    if (ds.Length > 0)
                    {
                        //处理每个文件夹
                        foreach (var d in ds)
                        {
                            //先找出所有txt，把他们都删除
                            var txtfiles = BasicFilesOperation.YXHGetAllextFiles(d.FullName, "*.txt");
                            if (txtfiles.Length > 0)
                            {
                                foreach (var item in txtfiles)
                                {
                                    item.FullName.YXHDeleteFile();
                                }
                            }
                            //再找出所有csv文件
                            var csvfiles = BasicFilesOperation.YXHGetAllextFiles(d.FullName, "*.csv");
                            //删除所有0kb的csv文件
                            csvfiles.YXHDeleteZeroCsv();
                            //再获得所有csv文件信息，这个时候已经把所有txt，0kb的去除掉了
                            var csvlist = BasicFilesOperation.YXHGetAllextFiles(d.FullName, "*.csv");
                            //存储2024_03_14-15_51_43-1-F中的1序号
                            List<int> index = new List<int>();
                            //把每一个文件名中的序号存进index
                            foreach (var csv in csvfiles)
                            {
                                var idx=csv.Name.Split('-')[2];
                                var t=int.TryParse(idx, out int num);
                                if (t)
                                {
                                    index.Add(num);
                                }
                                else
                                {
                                    list.Add("文件名有错误");
                                    return list;
                                }

                            }
                            //获得删除的序号集合的集合
                            var delindex= index.YXHGetCsvIndex();
                            if(delindex.Count > 0)
                            {
                                //每个集合去进行删除
                                foreach (var idx in delindex)
                                {
                                    if (idx.Count > 0)
                                    {
                                        foreach (var item in idx)
                                        {
                                            csvlist[item].FullName.YXHDeleteFile();
                                        }
                                    }
                                }
                            }
                            //再获得csv文件信息，接下来要进行清洗，线性转换，去毛刺等操作
                            csvlist = BasicFilesOperation.YXHGetAllextFiles(d.FullName, "*.csv");
                            //定义输出目录日期文件夹
                            string resultdirectorypath = Path.Combine(row.savedatapath, d.Name);
                            DirectoryInfo root = new DirectoryInfo(resultdirectorypath);
                            //处理每一个文件
                            for (int i = 0; i < csvlist.Length; i++)
                            {
                                var result = await CSVOperator.YXHReadCSV2ListOneTime(csvlist[i]);//读取csv数据到List<string>,每一行为一个string
                                //输出文件夹路径如果没有则创建
                                if (!root.Exists)
                                {
                                    root.Create();
                                }
                                //获得每一个处理完的文件的完整输出路径
                                string singleresultpath = Path.Combine(root.FullName, csvlist[i].Name);
                                //进行清洗
                                for (int j = 1; j < result.Count; j++)
                                {
                                   
                                    //先进行异常整数值的清洗
                                    if (cleannumreg.Length > 0)
                                    {
                                        foreach (var r in cleannumreg)
                                        {
                                            result[j] = Regex.Replace(result[j], @"(?<![\d.-])\" + r + @"(?![\d.-])", "0");
                                        }
                                    }
                                    else
                                    {
                                        list.Add("清洗整数规则配置错误");
                                        return list;
                                    }
                                    if (cleanstringreg.Length > 0)
                                    {
                                        foreach (var r in cleanstringreg)
                                        {
                                            //把字符串类型的也清零
                                            result[j] = result[j].Replace(r, "0");
                                        }
                                    }
                                    else
                                    {
                                        list.Add("清晰字符串规则配置错误");
                                        return list;
                                    }
                                    result[j] = Regex.Replace(result[j], ",,", ",0,");
                                    //result[j] = ReplaceAtIndex(result[j], gpsspdindex, canspdindex);
                                    //做线性变换，如果有的话
                                    if (row?.linearConvertModals?.Count > 0)
                                    {
                                        var values = result[i].Split(',');
                                        foreach (var conversion in row?.linearConvertModals)
                                        {
                                            int oldIndex = conversion.oldchanidx;
                                            int newIndex = conversion.newchanidx;
                                            double oldValue = double.Parse(values[oldIndex]);
                                            double newValue = oldValue * conversion.k + conversion.b;
                                            values[newIndex] = newValue.ToString();
                                        }
                                        result[j] = string.Join(",", values);
                                    }
                                }
                                
                            }
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 从csv名称中判断需要删除的csv的index的合集
        /// </summary>
        /// <param name="data">csv文件名中的序号集合</param>
        /// <returns></returns>
        public static List<List<int>> YXHGetCsvIndex(this List<int> data)
        {
            List <List<int>> result= new List<List<int>>();
            for (int i = 1; i < data.Count; i++)
            {
                if (data[i] == 1)
                {
                    if (data[i - 1] < 61)
                    {
                        //这是每个1前面的那个数的值，如果小与61，则把之前1到这个数之间的index记录下来
                        var t = data[i - 1];
                        //这个是这个数的index
                        var end = i - 1;
                        var start = i -t;
                        List<int> list = new List<int>();
                        for (int j = start; j <= end; j++)
                        {
                            list.Add(j);
                        }
                        result.Add(list);
                    }
                }
            }
            return result;
        }
    }
}
